// 云函数入口文件
const cloud = require('wx-server-sdk')
const tencentcloud = require("tencentcloud-sdk-nodejs")

// 初始化 cloud
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 初始化 SMS 客户端
const SmsClient = tencentcloud.sms.v20210111.Client
const client = new SmsClient({
  credential: {
    secretId: "您的secretId",
    secretKey: "您的secretKey"
  },
  region: "ap-guangzhou",
  profile: {
    signMethod: "TC3-HMAC-SHA256",
    httpProfile: {
      reqMethod: "POST",
      reqTimeout: 30,
      endpoint: "sms.tencentcloudapi.com"
    }
  }
})

// 生成6位随机验证码
function generateCode() {
  return Math.floor(100000 + Math.random() * 900000).toString()
}

// 云函数入口函数
exports.main = async (event, context) => {
  const { phoneNumber } = event
  const code = generateCode()
  
  try {
    // 将验证码保存到云数据库
    const db = cloud.database()
    await db.collection('sms_codes').add({
      data: {
        phoneNumber,
        code,
        createTime: db.serverDate(),
        expireTime: db.serverDate({
          offset: 5 * 60 * 1000 // 5分钟有效期
        })
      }
    })

    // 发送短信
    const params = {
      PhoneNumberSet: [`+86${phoneNumber}`],
      SmsSdkAppId: "您的SmsSdkAppId",
      SignName: "您的签名名称",
      TemplateId: "您的模板ID",
      TemplateParamSet: [code, "5"], // 验证码和有效期（分钟）
    }

    const result = await client.SendSms(params)
    
    return {
      success: true,
      result
    }
  } catch (err) {
    console.error('发送短信失败：', err)
    return {
      success: false,
      error: err
    }
  }
} 